package com.demo.web;

import com.demo.config.tus.TusFileUploadResolver;
import lombok.extern.slf4j.Slf4j;
import me.desair.tus.server.TusFileUploadService;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Param;
import org.noear.solon.core.Props;
import org.noear.solon.core.handle.MethodType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Slf4j
@Controller
@Mapping("/upload")
public class UploadController {

    @Mapping(method = MethodType.ALL, value = "/{fileId}/**")
    public void upload(@Param(value = "fileId") String fileId, HttpServletRequest request, HttpServletResponse response) {

        final Props tusProperties = Solon.cfg().getProp("tus");
        final TusFileUploadService tusFileUploadService = new TusFileUploadService();
        tusFileUploadService.withUploadURI("/upload/"+fileId+"/");
        tusFileUploadService.withStoragePath(tusProperties.get("chunkFilePath"));
        if (tusProperties.getBool("enableClean",false)) {
            tusFileUploadService.withUploadExpirationPeriod(Duration.parse(tusProperties.get("expireTime")).toMillis());
        }


        TusFileUploadResolver tusFileUploadResolver =new TusFileUploadResolver(tusFileUploadService,tusProperties);


        tusFileUploadResolver.upload(request, response,fileId);
    }
}
